<?php
/**
 * 存量媒资导入
 */
include_once dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR.'public.class.php';
include_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'vod_v2' . DIRECTORY_SEPARATOR . 'vod_v2.class.php';
include_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'vod_index' . DIRECTORY_SEPARATOR . 'vod_index.class.php';
include_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'vod_media' . DIRECTORY_SEPARATOR . 'vod_media.class.php';
include_once dirname(dirname(dirname(__FILE__))) . DIRECTORY_SEPARATOR . 'nn_cms_db' . DIRECTORY_SEPARATOR . 'nns_depot' . DIRECTORY_SEPARATOR . 'nns_db_depot_class.php';

class nl_stock_import extends nl_public
{
	static public $import_source = 'mgtv';
	
	/**
	 * 解析导入的主媒资CSV文件
	 * @param $dc DC模块
	 * @param $vod_info vod信息
	 * $vod_info = array(
		 'nns_asset_import_id' => 注入ID,
		 'nns_name' => 注入名称,
		 'nns_pinyin' => 拼音首字母,
		 'nns_asset_category' => 一级栏目,
		 'nns_director' => 导演,
		 'nns_actor' => 演员,
		 'nns_kind' => 类型,
		 'nns_keyword' => 关键字,
		 'nns_area' => 地区,
		 'nns_all_index' => 总集数,
		 'nns_summary' => $简介,
		 'nns_language' => 语言,
		 'nns_show_time' => 上映时间,
		 'nns_producer' => 提供商,
		 'nns_cp_id' => 来源ID,
		);
	 * @param $source_id   上游来源ID
	 * @return string
	 */
	static public function stock_video_import($dc,$vod_info,$source_id)
	{
		if(empty($vod_info) || !is_array($vod_info))
		{
			return self::return_data(1,'参数错误');
		}
		$vod_info['nns_pinyin_length'] = strlen($vod_info['nns_pinyin']);
		$vod_info['nns_import_source'] = self::$import_source;
		if(!empty($vod_info['nns_asset_category']))
		{
			$view = self::set_view_type($vod_info['nns_asset_category']);
			$vod_info['nns_view_type'] = $view['data_info'];
			if(get_config_v2('g_category_v2'))
            {
                $depot_info = self::set_depot_category_v2($vod_info['nns_asset_category']);
            }
            else
            {
                $depot_info = self::set_depot_category($vod_info['nns_asset_category']);
            }
			$vod_info['nns_depot_id'] = $depot_info['data_info']['id'];
			$vod_info['nns_category_id'] = $depot_info['data_info']['category'];
			$vod_info['nns_org_id'] = $depot_info['data_info']['org_id'];
			unset($vod_info['nns_asset_category']);
		}
		//根据注入ID查询是否存在
		$vod_re = nl_vod_v2::query_vod_info_by_import_id($dc, $vod_info['nns_asset_import_id'],$source_id);
		if($vod_re['ret'] != 0)
		{
			return $vod_re;
		}
		if(is_array($vod_re['data_info'])) //存在vod数据，则进行修改
		{
			 $modify_re = nl_vod_v2::edit($dc,$vod_info,$vod_re['data_info'][0]['nns_id']);
			 if($modify_re['ret'] != 0)
			 {
			 	return $modify_re;
			 }
			 $vod_id = $vod_re['data_info'][0]['nns_id'];
		}
		else//不存在vod数据，则添加
		{
			$vod_info['nns_id'] = np_guid_rand();
			$add_re = nl_vod_v2::add($dc, $vod_info);
			if($add_re['ret'] != 0)
			{
				return $add_re;
			}
			$vod_id = $vod_info['nns_id'];
		}
		$return_arr = array(
				'vod_id' => $vod_id,
		);
		return self::return_data(0,'OK',$return_arr);
	}
	/**
	 * 导入分集CSV
	 * @param unknown $dc
	 * @param unknown $vod_index_info
	 * @param unknown $asset_import_id
	 * @param unknown $source_id
	 * @return array('ret'=>'状态码','reason'=>'原因','data'=>'数据')|Ambigous
	 */
	static public function stock_index_import($dc, $vod_index_info,$asset_import_id, $source_id)
	{
		if(empty($vod_index_info) || !is_array($vod_index_info))
		{
			return self::return_data(1,'参数错误');
		}
		$vod_index_info['nns_import_source'] = self::$import_source;
		//根据主媒资注入ID查询是否存在
		$vod_re = nl_vod_v2::query_vod_info_by_import_id($dc, $asset_import_id,$source_id);
		if($vod_re['ret'] != 0 || !is_array($vod_re['data_info']))
		{
			return $vod_re;
		}
		$vod_index_info['nns_vod_id'] = $vod_re['data_info'][0]['nns_id'];
		//根据分集注入ID查询是否存在
		$vod_index_re = nl_vod_index_v2::query_vod_index_info_by_import_id($dc, $vod_index_info['nns_import_id'],$source_id);
		if($vod_index_re['ret'] != 0)
		{
			return $vod_index_re;
		}
		if(is_array($vod_index_re['data_info'])) //存在vod_index数据，则进行修改
		{
			$modify_re = nl_vod_index_v2::edit($dc,$vod_index_info,$vod_index_re['data_info'][0]['nns_id']);
			if($modify_re['ret'] != 0)
			{
				return $modify_re;
			}
			$vod_index_id = $vod_index_re['data_info'][0]['nns_id'];
		}
		else//不存在vod数据，则添加
		{
			$vod_index_info['nns_id'] = np_guid_rand();
			$add_re = nl_vod_index_v2::add($dc, $vod_index_info);
			if($add_re['ret'] != 0)
			{
				return $add_re;
			}
			$vod_index_id = $vod_index_info['nns_id'];
		}
		$return_arr = array(
				'vod_id' => $vod_index_info['nns_vod_id'],
				'vod_name' => $vod_re['data_info'][0]['nns_name'],
				'index_id' => $vod_index_id
		);
		return self::return_data(0,'OK',$return_arr);
	}
	/**
	 * 导入片源CSV
	 * @param unknown $dc
	 * @param unknown $vod_media_info
	 * @param unknown $asset_import_id
	 * @param unknown $index_import_id
	 * @param unknown $source_id
	 * @return array('ret'=>'状态码','reason'=>'原因','data'=>'数据')|Ambigous
	 */
	static public function stock_media_import($dc, $vod_media_info,$asset_import_id, $index_import_id, $source_id)
	{
		if(empty($vod_media_info) || !is_array($vod_media_info))
		{
			return self::return_data(1,'参数错误');
		}
		$vod_media_info['nns_import_source'] = self::$import_source;
		$vod_media_info['nns_type'] = 1;
		$vod_media_info['nns_state'] = 0;
		$vod_media_info['nns_media_caps'] = 'VOD';
		$vod_media_info['nns_dimensions'] = 0;
		//根据主媒资注入ID查询是否存在
		$vod_re = nl_vod_v2::query_vod_info_by_import_id($dc, $asset_import_id,$source_id);
		if($vod_re['ret'] != 0 || !is_array($vod_re['data_info']))
		{
			return $vod_re;
		}
		$vod_media_info['nns_vod_id'] = $vod_re['data_info'][0]['nns_id'];
		//根据分集注入ID查询是否存在
		$vod_index_re = nl_vod_index_v2::query_vod_index_info_by_import_id($dc, $index_import_id,$source_id);
		if($vod_index_re['ret'] != 0)
		{
			return $vod_index_re;
		}
		$vod_media_info['nns_vod_index_id'] = $vod_index_re['data_info'][0]['nns_id'];
		$vod_media_info['nns_vod_index'] = $vod_index_re['data_info'][0]['nns_index'];
		//根据片源注入ID查询是否存在
		$vod_media_re = nl_vod_media_v2::query_vod_media_info_by_import_id($dc, $vod_media_info['nns_import_id'],$source_id);
		if($vod_media_re['ret'] != 0)
		{
			return $vod_media_re;
		}
		if(is_array($vod_media_re['data_info'])) //存在vod_media数据，则进行修改
		{
			$modify_re = nl_vod_media_v2::edit($dc,$vod_media_info,$vod_media_re['data_info'][0]['nns_id']);
			if($modify_re['ret'] != 0)
			{
				return $modify_re;
			}
			$vod_media_id = $vod_media_re['data_info'][0]['nns_id'];
		}
		else//不存在vod数据，则添加
		{
            $vod_media_info['nns_id'] = np_guid_rand();
			$add_re = nl_vod_media_v2::add($dc, $vod_media_info);
			if($add_re['ret'] != 0)
			{
				return $add_re;
			}
			$vod_media_id = $vod_media_info['nns_id'];
		}
		$return_arr = array(
				'vod_id' => $vod_media_info['nns_vod_id'],
				'vod_name' => $vod_re['data_info'][0]['nns_name'],
				'index_id' => $vod_media_info['nns_vod_index_id'],
				'index_name' => $vod_index_re['data_info'][0]['nns_name'],
				'media_id' => $vod_media_id
		);
		return self::return_data(0,'OK',$return_arr);
	}
	/**
	 * 根据媒资类型生成一级栏目
	 * @param unknown $category_name
	 * @param number $depot_type
	 * @param string $parent_id
	 * @return multitype:unknown NULL |multitype:unknown number |boolean
	 */
	static public function set_depot_category($category_name, $depot_type = 0, $parent_id = '10000')
	{
		$depot_inst = new nns_db_depot_class();
		$depot_result = $depot_inst->nns_db_depot_info(0, NULL, $depot_type);

		$org_id = $depot_result['data'][0]['nns_org_id'];
		$org_type = $depot_result['data'][0]['nns_org_type'];
		$depot_id = $depot_result['data'][0]['nns_id'];
		$depot_info = $depot_result['data'][0]['nns_category'];
		//加载xml
		$dom = new DOMDocument('1.0', 'utf-8');
		$dom->loadXML($depot_info);
		$category_id_arr = array();
		$categorys = $dom->getElementsByTagName('category');
		$flag = true;
		foreach ($categorys as $category)
		{
			//栏目名称和栏目父节点同时相同才认为存在该栏目，允许不同栏目级别下面的栏目名称相同
			$parent = $parent_id == '10000' ? 0 : $parent_id;
			if($category->getAttribute('name') == $category_name && $category->getAttribute('parent') == (string)$parent)
			{
				$flag = false;
			}
			if ($category->getAttribute('name') === $category_name && $category->getAttribute('parent') === (string)$parent)
			{
				$category_id = $category->getAttribute('id');
				$arr_cate = array(
						'id' => $depot_id,
						'category' => $category_id,
						'org_id' => $org_id,
						'name' => $category->getAttribute('name')
				);
				return self::return_data(0,'OK',$arr_cate);
			}
			else
			{
				$category_id_arr[$category->getAttribute('id')] = $category->getAttribute('id');
			}
		}
		$category_parent = $parent_id == 10000 ? 0 : $parent_id;
		$category_id = $parent_id * 1000;
		foreach ($category_id_arr as $key => $val)
		{
			if (strlen($category_id) != strlen($val))
			{
				unset($category_id_arr[$key]);
			}
		}
		for ($i = 1; $i < 1000; $i++)
		{
			$category_id = $category_id + $i;
			if (!array_key_exists((string)$category_id, $category_id_arr))
			{
				break;
			}
		}
		//创建栏目
		$bool = true;
		if ($category_parent != 0)
		{
			foreach ($categorys as $item)
			{
				if ($item->getAttribute("id") === $category_id)
				{
					$bool = false;
					break;
				}
			}
			if ($bool)
			{
				foreach ($categorys as $item)
				{
					if ($item->getAttribute("id") === (string)$category_parent)
					{
						$item_new = $dom->createElement("category");
						$item_new->setAttribute("id", $category_id);
						$category_name = str_replace("<", "", $category_name);
						$category_name = str_replace("/>", "", $category_name);
						$category_name = str_replace("\"", "", $category_name);
						$category_name = str_replace("'", "", $category_name);
						$item_new->setAttribute("name", $category_name);
						$item_new->setAttribute("parent", $category_parent);
						$item->appendChild($item_new);
						break;
					}
				}
			}
		}
		else
		{
			foreach ($categorys as $item)
			{
				if ($item->getAttribute("id") === $category_id)
				{
					$bool = false;
					break;
				}
			}
			if ($bool)
			{
				$item_new = $dom->createElement("category");
				$item_new->setAttribute("id", $category_id);
				$item_new->setAttribute("name", $category_name);
				$item_new->setAttribute("parent", $category_parent);
				$dom->firstChild->appendChild($item_new);
			}
		}
        $xml_data = $dom->saveXML();
		//修改栏目
		$result = $depot_inst->nns_db_depot_modify('', $xml_data, $org_type, $org_id, $depot_type);
		//修改栏目成功
		if ($result['ret'] == '0')
		{
			$arr_cate =  array(
					'id' => $depot_id,
					'category' => $category_id,
					'org_id' => $org_id,
					'name' => $category_name
			);
			return self::return_data(0,'OK',$arr_cate);
		}
		return self::return_data(1,'fail');
	}
	/**
	 * 根据类型获取view_type
	 * @param unknown $asset_category
	 * @return array('ret'=>'状态码','reason'=>'原因','data'=>'数据')
	 */
	static public function set_view_type($asset_category)
	{
		$video_type = get_config_v2("g_video_main_type");
		$view_type = 0;
		foreach ($video_type as $key=>$val)
		{
			if($val === $asset_category)
			{
				$view_type = $key;
				break;
			}
		}
		return self::return_data(0,'OK',$view_type);
	}
    /**
     * 根据媒资类型生成一级栏目V2
     * @param unknown $category_name
     * @param number $depot_type
     * @param string $parent_id
     * @return multitype:unknown NULL |multitype:unknown number |boolean
     */
    static public function set_depot_category_v2($str_category_name, $int_depot_type = 0, $str_parent_id = "")
    {
        $obj_re = array();

        if(empty($str_category_name) && strlen($str_category_name) <= 0)
        {
            return self::return_data(NS_CDS_FAIL, '资源库栏目名称为空');
        }

        //查询媒资库信息
        $arr_depot_ret = \nl_depot::get_depot_info(\m_config::get_dc(), array('nns_type' => $int_depot_type));
        if ($arr_depot_ret['ret'] != NS_CDS_SUCCE || !is_array($arr_depot_ret['data_info']) || count($arr_depot_ret['data_info']) < 1)
        {
            return self::return_data(NS_CDS_FAIL, 'func[set_depot_category]查询栏目信息失败');
        }
        $str_org_id = $arr_depot_ret['data_info'][0]['nns_org_id'];
        $str_depot_id = $arr_depot_ret['data_info'][0]['nns_id'];

        //如果父级栏目不为空
        if(!empty($str_parent_id) || strlen($str_parent_id) > 0)
        {
            //根栏目的父级栏目默认为0
            $str_parent_id_2 = $str_parent_id == '10000' ? '0' : $str_parent_id;
            $arr_where = array(
                'nns_type' => $int_depot_type,
                'nns_name' => $str_category_name,
                'nns_parent_id' => $str_parent_id_2,
            );
        }
        else
        {
            $arr_where = array('nns_type' => $int_depot_type,'nns_name' => $str_category_name);
            $str_parent_id_2 = $arr_where['nns_parent_id'];
            $str_parent_id = $str_parent_id_2 == 0 ? '10000' : $str_parent_id_2;
        }

        //根据栏目类型和父级ID查询媒资栏目信息
        $arr_category_ret = \nl_depot_v2::query(\m_config::get_dc(), $arr_where, 'nns_category_id,nns_name,nns_parent_id,nns_depot_id,nns_org_id','nns_order desc,nns_category_id asc');

        //查询成功
        if($arr_category_ret['ret'] == NS_CDS_SUCCE)
        {
            //匹配成功
            if(!empty($arr_category_ret['data_info']) && is_array($arr_category_ret['data_info']))
            {
                $category = $arr_category_ret['data_info'][0];
                //当第三方注入时,通过注入id查询到数据
                if ($category['nns_name'] != $str_category_name)
                {//当名称不一样时，修改名称
                    $st = nl_depot_v2::edit(\m_config::get_dc(), $category['nns_category_id'], $str_depot_id, $int_depot_type, array('nns_name' => $str_category_name),true);
                    if ($st['ret'] != NS_CDS_SUCCE)
                    {
                        return $st;
                    }
                }
                $obj_re = array(
                    'nns_id'         => $category['nns_depot_id'],
                    'nns_category_id'=> $category['nns_category_id'],
                    'nns_org_id'     => $category['nns_org_id'],
                    'nns_type'       => $int_depot_type
                );
            }
            //匹配失败
            else
            {
                $category_id = self::_get_depot_category_id($str_parent_id, $int_depot_type);
                //创建媒资栏目
                if($str_parent_id_2 != 0)
                {
                    $str_category_name = str_replace("<", "", $str_category_name);
                    $str_category_name = str_replace("/>", "", $str_category_name);
                    $str_category_name = str_replace("\"", "", $str_category_name);
                    $str_category_name = str_replace("'", "", $str_category_name);
                }
                //构建添加参数的数组
                $arr_add = array(
                    'nns_order' => 0,
                    'nns_org_id'=> $str_org_id,
                    'nns_type' => $int_depot_type,
                    'nns_depot_id' => $str_depot_id,
                    'nns_name' => $str_category_name,
                    'nns_category_id' => $category_id,
                    'nns_parent_id'=> $str_parent_id_2,
                );
                //执行添加SQL
                $arr_add_ret = \nl_depot_v2::add(\m_config::get_dc(), $arr_add);
                if($arr_add_ret['ret'] == NS_CDS_SUCCE)
                {
                    $obj_re = array(
                        'nns_id'         => $arr_add['nns_depot_id'],
                        'nns_category_id'=> $arr_add['nns_category_id'],
                        'nns_org_id'     => $arr_add['nns_org_id'],
                        'nns_type'       => $int_depot_type
                    );
                }
                else
                {
                    return self::return_data(NS_CDS_FAIL, 'func[set_depot_category]创建媒资库栏目失败。' . $arr_add_ret['reason']);
                }
                unset($arr_add);
            }
        }
        else
        {
            return self::return_data(NS_CDS_FAIL, 'func[set_depot_category]查询媒资库栏目失败');
        }
        $obj_re_re = array(
            'id' => $obj_re['nns_id'],
            'category' => $obj_re['nns_category_id'],
            'org_id' => $obj_re['nns_org_id'],
            'name' => $str_category_name,
        );
        //删除变量，释放内存
        unset($str_parent_id_2);

        return self::return_data(NS_CDS_SUCCE, '成功', $obj_re_re);
    }
    /**
     * 生成媒资库栏目ID
     * @param string $str_parent_id   父级栏目ID
     * @param int    $int_depot_type  媒资库类型。0点播1直播
     * @return string
     * xinxin.deng 2018/12/4 16:50
     */
    static private function _get_depot_category_id($str_parent_id,$int_depot_type = 0)
    {
        //查询该父级栏目下所有的一级子栏目
        $arr_child_category_ret = nl_depot_v2::query(\m_config::get_dc(),
            array(
                'nns_type' => $int_depot_type,
                'nns_parent_id' => $str_parent_id == '10000' ? '0' : $str_parent_id,
            ),'nns_category_id','nns_order desc,nns_category_id asc');

        $arr_child_category = np_array_rekey($arr_child_category_ret['data_info'],'nns_category_id');

        $category_id = $str_parent_id ."000";
        //生成栏目ID
        $i = 1;
        while($i < 1000)
        {
            $category_id = $str_parent_id . sprintf("%03d",$i);
            if (!array_key_exists($category_id, $arr_child_category))
            {
                break;
            }
            $i++;
        }

        return $category_id;
    }
}